<?php
class Utils {
	public static function loadJs($path){
		$baseUrl = Yii::app()->request->baseUrl;
		Yii::app()->getClientScript()->registerScriptFile("$baseUrl$path");
	}
	
	public static function loadCss($path){
		$baseUrl = Yii::app()->request->baseUrl;
		Yii::app()->getClientScript()->registerCssFile("$baseUrl$path");
	}
	
	public static function displayErr($model,$attribute){
		if($model->getError($attribute)){
			echo "<span class='label important'>".$model->getError($attribute)."</span>";
		}
	}
	
	//Template engine. Replace all the occurance of {var} by the values in the array $vars
	public static function template($template,$vars) {
		$return = $template;
		foreach ($vars as $var){
			$return = preg_replace("/{var}/",$var,$return,1);
		}
		return $return;
	}

	//Get the absolute file path from a relative path. 
	//Input: "/images/cover/1.png". Output: "D:/www/webapp/protected/../images/cover/1.png"
	public static function getFilePath($relativePath){
		return Yii::app()->basePath ."/../". $relativePath;
	}

	//Get the weburl from a relative path
	//Input: "/images/cover/1.png". Output: "http//localhost/webapp/images/cover/1.png"
	public static function getFileUrl($relativePath){
		return Yii::app()->baseUrl . $relativePath;
	}
	
	//Get the location of a image by folder,type and id. Example return value: D:/www/webapp/images/floder/type.id.png
	public static function getImagePathById($folder,$type,$id){
		return Utils::getFilePath(Utils::template(Constants::$image_path, array($folder,$type,$id)));
	}	
	
	//Get the web url of a image by folder, type and id. Example return value: /floder/type.id.png
	public static function getImageUrlById($folder,$type,$id){
		if (file_exists(Utils::getImagePathById($folder, $type, $id))){
			$filepath_relative = Utils::template(Constants::$image_path, array($folder,$type,$id));
			return Utils::getFileUrl($filepath_relative);
		}else{
			return Utils::getFileUrl(Utils::template(Constants::$image_path, array($folder,$type,"default")));
		}
	}
	
	//Display a button if necessary
	public static function displayBtn($btn){
		if(!Yii::app()->user->isGuest && (Yii::app()->user->name == $_GET['username'] || Utils::isAdmin())){
			echo $btn;
			return true;
		}
	}
	
	//Check if a member is an admin
	public static function isAdmin(){
		if(Yii::app()->user->isGuest){
			return false;
		}
		$member = Member::model()->findByPk(Yii::app()->user->id);
		if(!empty($member) && $member->type == Member::TYPE_ADMIN){
			return true;
		}
	}
}